class @AdminUserListingView extends ListingView

    el: $('#content')

    initialize: ->
        super
        @model.bind("change", @render)
        @model.fetch()

    render: ->
        @Navigate(@model.url(), false, true)

        @GetTemplate(SiteMap.Admin.Users.ListingTemplate, (compiledTemplate)=>
            $(@el).html(compiledTemplate(@model.toJSON()))
        )

    events:
        "click .search": "search"
        "click .pagination a": "pagination"
        "click th>a": "sort"
        "click .buttons>.create": "create"
        "click .buttons>.delete": "remove"
        "click tbody tr>td:not(.chk)": "edit"
        "change .page-size": "changeSize"
        "click .reset": "reset"

    search: (event) ->
        event.preventDefault()
        email = $("#Filter_Email").val()
        login = $("#Filter_Login").val()

        if (email? and email != '') || (login? and login != '')
            Messages.WriteMessage('Apply search.')
            Loading.Start()
            @model.set({"Filter": {Email:email, Login:login}}, { silent: true })
            @model.fetch()

    reset: (event) ->
        Loading.Start()
        $("#Filter_Email").val('')
        $("#Filter_Login").val('')
        @model.set({"Filter":{"Email": '',"Login": ''}}, { silent: true })
        @model.fetch()

    remove: (event) ->
        event.preventDefault()
        Messages.Clear()
        form = $(@el).find("form.listing")
        if form.find("input:checked").length
           confirmDialog = new UserDeleteConfirm(@)
           confirmDialog.Show("Are you sure?")
        else
            Messages.WriteMessage("Choose one or more users.")

     create: (event) ->
        event.preventDefault()
        Loading.Start()
        @Navigate(SiteMap.Admin.Users.Create, true)

class UserDeleteConfirm extends ConfirmDialog
    constructor: (view) ->
        @view = view
    Ok: ->
        form = $(@view.el).find("form.listing")
        data = form.serialize()
        Loading.Start()
        Messages.WriteMessage("Deleting users")
        $.post(SiteMap.Admin.Users.Delete, data, (response)=>
            if (response.SuccessMessage? && response.SuccessMessage.length)
                Messages.WriteSuccessMessage(response.SuccessMessage)
                @view.model.fetch()
            else 
                Messages.WriteErrors(response.Errors)
                Loading.Stop()
        )
